package com.yanqu.road.dao.impl;

import com.alibaba.druid.util.JdbcUtils;
import com.yanqu.road.dao.db.DbMonitor;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class TempNoPoolDao {

    protected static Logger logger = LogManager.getLogger(TempNoPoolDao.class.getName());

    private String ip;
    private String port;
    private String dbName;
    private String user;
    private String password;

    private DbMonitor dbMonitor;
    private Connection connection = null;

    public TempNoPoolDao(String dbParam) {
        List<String> stringList = StringUtils.stringToStringList(dbParam, "\\|");
        if (stringList.size() != 5) {
            throw new RuntimeException("db connect param error! dbParam size no equals 5! dbParam = " + dbParam);
        }

        this.ip = stringList.get(0);
        this.port = stringList.get(1);
        this.dbName = stringList.get(2);
        this.user = stringList.get(3);
        this.password = stringList.get(4);
    }

    public synchronized Connection getConnection() {
        // 不能重复拿连接
        if (connection != null) {
            throw new RuntimeException("repeat Open Connection!");
        }

        dbMonitor = new DbMonitor();
        dbMonitor.openConnection();

        String url = "jdbc:mysql://" + ip + ":" + port + "/" + dbName + "?useUnicode=true&characterEncoding=utf8&useSSL=false";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            logger.error("db connection connect error! url={}, user={}, password={}", url, user, password);
            logger.error(e.getMessage(), e);

            JdbcUtils.close(connection);
            connection = null;
            dbMonitor.closeConnection();
        }
        return connection;
    }

    public synchronized void closeConnection(PreparedStatement pstmt, ResultSet rs) {

        JdbcUtils.close(rs);

        try {

            if (pstmt != null) {
                dbMonitor.execComplete(pstmt.toString());
            }
            if (pstmt != null && !pstmt.isClosed()) {
                pstmt.clearParameters();
            }

            if (!connection.isClosed()) {
                if (!connection.getAutoCommit()) {
                    connection.commit();
                    connection.setAutoCommit(true);
                }
            }
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
        } finally {
            JdbcUtils.close(pstmt);

            JdbcUtils.close(connection);
            connection = null;

            dbMonitor.closeConnection();
        }
    }

}
